import numpy as np
import matplotlib.pyplot as plt
from scipy.spatial import Voronoi, voronoi_plot_2d

if __name__ == '__main__':

    # 设置随机种子以便复现
    np.random.seed(42)

    # 生成随机点
    points = np.random.rand(10, 2)

    # 创建 Voronoi 分区
    vor = Voronoi(points)

    # 创建画布
    fig, ax = plt.subplots(1, 3, figsize=(12, 6))

    # 左侧：绘制原始点分布
    ax[0].scatter(points[:, 0], points[:, 1], c='black')
    ax[0].set_xlim(0, 1)
    ax[0].set_ylim(0, 1)
    ax[0].set_aspect('equal', adjustable='box')  # 保持正方形比例
    ax[0].set_title("original")
    ax[0].axis('off')
    for spine in ax[0].spines.values():
        spine.set_visible(False)  # 隐藏所有边框
    ax[0].spines['top'].set_visible(True)  # 显示上边框
    ax[0].spines['top'].set_color('black')  # 设置边框颜色
    ax[0].spines['top'].set_linewidth(2)  # 设置边框宽度

    # 中间：绘制箭头
    ax[1].annotate(
        '', xy=(0.7, 0.5), xytext=(0.3, 0.5),
        arrowprops=dict(facecolor='blue', shrink=0.05, width=12, headwidth=30)
    )
    ax[1].axis('off')

    # 右侧：绘制 Voronoi 分区
    voronoi_plot_2d(vor, show_vertices=False, show_points=False, ax=ax[2])
    for region in vor.regions:
        if not -1 in region and len(region) > 0:
            polygon = [vor.vertices[i] for i in region]
            ax[2].fill(*zip(*polygon), alpha=0.5)
    # for region_idx in vor.point_region:
    #     region = vor.regions[region_idx]
    #     if not -1 in region and len(region) > 0:  # 排除无穷远区域
    #         polygon = [vor.vertices[i] for i in region]
    #         ax[2].fill(*zip(*polygon), color=np.random.rand(3, ), alpha=0.6)  # 用随机颜色填充
    ax[2].scatter(points[:, 0], points[:, 1], c='black')
    ax[2].set_xlim(0, 1)
    ax[2].set_ylim(0, 1)
    ax[2].set_aspect('equal', adjustable='box')  # 保持正方形比例
    ax[2].set_title("Voronoi partition")
    ax[2].axis('off')

    # 显示图片
    plt.tight_layout()
    plt.show()